package com.kn.sys.service.impl;

import com.kn.common.model.Constant;
import com.kn.common.model.R;
import com.kn.sys.dao.PermissionDao;
import com.kn.sys.dto.CNode;
import com.kn.sys.dto.IdsDto;
import com.kn.sys.dto.PermissionDto;
import com.kn.sys.mapper.RolePermissiomMapper;
import com.kn.sys.model.RolePermissiomExample;
import com.kn.sys.service.BaseService;
import com.kn.sys.service.PermissionService;
import com.kn.sys.untils.CopyBean;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.params.shadow.com.univocity.parsers.annotations.Copy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.xml.ws.ServiceMode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends BaseService implements PermissionService {
    private final PermissionDao permissionDao;
    private final RolePermissiomMapper rolePermissiomMapper;

    @Override
    public R getRights() {
        return R.ok(permissionDao.getRights());
    }

    @Override
    public R rightsByRoleId(Long roleId) {
        List<Long> rights = permissionDao.rightsByRoleId(roleId);
        return R.ok(rights);
    }

    @Override
    public R savePermission(Long roleId, IdsDto[] idsDtos) {
        RolePermissiomExample rolePermissiomExample = new RolePermissiomExample();
        rolePermissiomExample.createCriteria().andRoleidEqualTo(roleId);
        rolePermissiomMapper.deleteByExample(rolePermissiomExample);
        List<IdsDto> idsDtosList = Arrays.asList(idsDtos);
        if (!CollectionUtils.isEmpty(idsDtosList)) {
            permissionDao.savePermission(idsDtosList);
        }
        return R.ok();
    }

    @Override/*return perms.stream()
                .filter(p -> p.getPid().equals(pid))
                .map(p -> {
                    final List<CNode> cNodes = generateTree(perms, p.getId());
                    final CNode cNode = CopyBean.copyBean(CNode::new, p);
                    if (!CollectionUtils.isEmpty(cNodes)) {
                        cNode.setChildren(cNodes);
                    }
                    return cNode;

                }).collect(Collectors.toList());*/
    public R getMenu() {
        List<PermissionDto> perms = permissionDao.getMenu(getUserId());
        List<CNode> cNodes = generateTree(perms, Constant.PID);
        return R.ok(cNodes);
    }

    private List<CNode> generateTree(List<PermissionDto> perms, long pid) {
      return   perms.stream()
              .filter(p -> p.getPid().equals(pid))
              .map(p ->{
         final    List<CNode> cNodes = generateTree(perms, p.getId());
          final   CNode cNode = CopyBean.copyBean(CNode::new, p);
            if (!CollectionUtils.isEmpty(cNodes)) {
                cNode.setChildren(cNodes);
            }
            return cNode;
                }).collect(Collectors.toList());

    }
}